import inquirer from 'inquirer';
import * as path from 'path';
import config from '../config';
import { copyDirectory, deleteDirectory, executeCmd, isDirectoryEmpty, trimPath } from '../utils';

export default async function (projectPath: string) {
    projectPath = trimPath(projectPath);
    console.log('项目路径: ' + projectPath);
    if (!projectPath || !isDirectoryEmpty(projectPath)) throw '请输入空文件夹路径';

    // 项目名数组
    const exampleNames = Object.keys(config.examples);
    if (exampleNames.length === 0) throw '没有可用的模版';

    const result = await inquirer.prompt<{ type: string }>([
        {
            name: 'type',
            type: 'list',
            message: '选择项目',
            default: exampleNames[0],
            choices: exampleNames
        }
    ]);

    // 模版临时目录
    const templatePath = path.join(__dirname, 'template');
    deleteDirectory(templatePath);

    // 下载源码
    const gitAddress = config.examples[result.type];
    console.log('拉取中: git clone ' + gitAddress);
    const code = await executeCmd('git', ['clone', '--depth=1', gitAddress, `"${templatePath}"`]);
    if (code != 0) {
        console.error('克隆失败, 检查git环境是否可用');
        return;
    }
    // 将模版拷贝至项目目录
    copyDirectory(templatePath, projectPath);
    deleteDirectory(templatePath);

    console.log(`创建成功`);
}